<?php

namespace App\Modules\Admin\Controllers;

use App\Models\Category;
use App\Modules\Admin\Requests\CategoryForm;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function category()
    {
        app('view')->prependNamespace('admin', resource_path('views/admin'));
        return view('admin::category');
    }

    public function deleteCategory(Request $request)
    {
        $id = $request->input('id');
        return response()->json(['status' => Category::destroy($id)]);
    }

    public function getCategories()
    {
        return response()->json(Category::orderBy('sort')->get()->toArray());
    }

    public function getCategory(Category $topics)
    {
        return response()->json([
            'id'          => $topics->id,
            'name'        => $topics->name,
            'description' => $topics->description,
            'sort'        => $topics->sort
        ]);
    }

    public function saveCategory(CategoryForm $request)
    {
        $id = $request->input('id');
        if (isset($id)) {
            $res = Category::where('id', $id)->update($request->all());
        } else {
            $res = Category::create($request->all());
        }

        if ($res) {
            $response = ['status' => true];
        } else {
            $response = ['status' => false, 'msg' => '网络异常，请稍后再试'];
        }
        return response()->json($response);
    }
}
